from django.core.management.base import BaseCommand
from src.abcarta import models
import os
import uuid
import shutil
from huadijianshe_website.settings import MEDIA_ROOT
import logging
logger = logging.getLogger('django')

class Command(BaseCommand):
    help = 'Migrate the usage info file to new website'

    def add_arguments(self, parser):
        parser.add_argument('--from-dirs', type=str, help="Migrate the usage info file to new website")

    def handle(self, *args, **options):
        from_dirs = options.get('from_dirs')

        if not from_dirs.startswith("/"):
            cwd = os.getcwd()
            from_dirs = cwd.rstrip("/")+"/"+from_dirs

        if os.path.isdir(from_dirs):
            for filename in os.listdir(from_dirs):
                filepath = os.path.join(from_dirs, filename)
                if os.path.isfile(filepath) and filepath.endswith(".pdf"):
                    item_num = filename.split(".")[0]
                    products = models.Products.objects.filter(item_num=item_num)
                    if products.count() == 1:
                        product = products.get(item_num=item_num)
                        pdf_name = str(uuid.uuid4()) + ".pdf"
                        pdf_url = "/guidebook/" + pdf_name
                        shutil.copy(filepath, MEDIA_ROOT + "/guidebook/" + pdf_name)
                        product.product_guide_book = "/media" + pdf_url
                        product.save()
                        logger.info("上传货号为: %s 的产品说明书成功!!!", item_num)
                    else:
                        logger.warn("货号为: %s 的产品不存在!!!,忽略", item_num)
        else:
            logger.error(from_dirs+"不是目录")